package com.junzhiit.nengji.app.web.controller;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.junzhiit.nengji.app.web.util.aliyun.AliyunOSSClientUtil;
import com.junzhiit.nengji.app.web.vo.ResultVO;

import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping(value = "/upload")
public class UploadController extends BaseController {

	@Value("${upload.temp}")
	private String tempPath;
	
	//阿里云API的bucket名称
	@Value("${oss.backet.name}")
	private String backetName;
	
	
	@ApiOperation(value = "上传分类图片")
	@RequestMapping(method = RequestMethod.POST)
	public ResultVO upload(MultipartFile file) {
		ResultVO result = new ResultVO();
		try {
			String fileName = file.getOriginalFilename();
			String prefix=fileName.substring(fileName.lastIndexOf("."));
		    fileName = UUID.randomUUID().toString().replaceAll("-", "") + prefix;
			String uploadName = AliyunOSSClientUtil.uploadObject2OSS(file.getInputStream(),fileName,backetName, tempPath);
			result.setData(uploadName);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("上传失败" + e.getMessage(), e);  
		}
		return null;
	}
	
	@ApiOperation(value = "上传分类图片")
	@RequestMapping(value="/base64",method = RequestMethod.POST)
	public ResultVO upload(String fileName,String base64) {
		ResultVO result = new ResultVO();
		try {
			byte[] base64Byte = Base64Utils.decodeFromString(base64);
			InputStream sbs = new ByteArrayInputStream(base64Byte); 
			String prefix=fileName.substring(fileName.lastIndexOf("."));
		    fileName = UUID.randomUUID().toString().replaceAll("-", "") + prefix;
			String uploadName = AliyunOSSClientUtil.uploadObject2OSS(sbs,fileName,backetName, tempPath);
			result.setData(uploadName);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("上传失败" + e.getMessage(), e);  
		}
		return null;
	}

	@ApiOperation(value = "删除分类图片")
	@RequestMapping(method = RequestMethod.DELETE)
	public ResultVO delete(String filefullPath) {
		ResultVO result = new ResultVO();
		boolean flag = AliyunOSSClientUtil.removeFile(backetName,tempPath + filefullPath);
		result.setData(flag);
		return result;
	}
	
	
}
